<template>
  <div>
    <!-- 搜索 & 新增管理员 -->
    <div class="toolbar">
      <!-- 按角色筛选 -->
      <el-select
          v-model="filters.role"
          placeholder="身份类型"
          clearable
          style="width: 140px; margin-right: 12px"
          @change="fetchAdmins"
      >
        <el-option label="全部" value="" />
        <el-option label="管理员" value="管理员" />
        <el-option label="健康管家" value="健康管家" />
      </el-select>

      <!-- 按姓名搜索 -->
      <el-input
          v-model="filters.name"
          placeholder="按姓名搜索"
          clearable
          @clear="fetchAdmins"
          @keyup.enter="fetchAdmins"
          style="width: 240px; margin-right: 12px"
      >
        <template #append>
          <el-button @click="fetchAdmins">
            <el-icon><Search/></el-icon>
          </el-button>
        </template>
      </el-input>


      <el-button type="primary" @click="openCreateDialog">
        新增用户
      </el-button>
    </div>

    <!-- 管理员表格 -->
    <el-table
        :data="admins"
        v-if="admins.length"
        stripe
        border
        style="width: 100%; margin-top: 16px"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="adName" label="姓名" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="role" label="角色" />
      <el-table-column label="操作" width="300">
        <template #default="{ row }">
          <el-button size="small"  type="warning" @click="toEdit(row.adId)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDelete(row.adId)">
            删除
          </el-button>
          <!-- 重置按钮改成蓝色 primary -->
          <el-button
              size="small"
              type="success"
              @click="confirmResetPassword(row.adId)"
          >
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-else class="empty">暂无数据</div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="adminPagination.total"
          v-model:current-page="adminPagination.current"
          v-model:page-size="adminPagination.size"
          :page-sizes="[6, 10, 20, 50]"
          @current-change="handleAdminPageChange"
          @size-change="handleAdminSizeChange"
      />
    </div>

    <!-- 新增/编辑管理员 Dialog -->
    <!-- 新增/编辑管理员 Dialog -->
    <el-dialog
        :title="isEditing ? '编辑用户' : '新增用户'"
        v-model="showEditDialog"
        width="520px"
        custom-class="admin-dialog"
        @close="resetForm"
    >
      <el-form
          :model="form"
          label-width="100px"
          class="admin-form"
          :rules="rules"
          ref="adminForm"
      >
        <!-- 角色选择 -->
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="管理员" />
            <el-option label="健康管家" value="健康管家" />
          </el-select>
        </el-form-item>

        <!-- 自动密码规则提示：仅在新增模式显示 -->
        <div
            v-if="!isEditing"
            style="font-size: 12px; color:#409eff; margin: -8px 0 12px 100px;"
        >
          {{ form.role === '管理员'
            ? '密码将设为与账号一致'
            : '密码将设为手机号后6位' }}
        </div>


        <!-- 账号输入框 - 仅管理员显示 -->
        <el-form-item
            v-if="form.role === '管理员'"
            label="账号"
            prop="adAccount"
        >
          <el-input
              v-model="form.adAccount"
              placeholder="请输入登录账号"
          />
        </el-form-item>

        <el-form-item label="姓名" prop="adName">
          <el-input v-model="form.adName" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input
              v-model="form.phone"
              placeholder="请输入电话"
              @blur="syncPasswordFromPhone"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button size="medium" @click="showEditDialog = false">
            取消
          </el-button>
          <el-button
              size="medium"
              type="primary"
              @click="submitForm"
          >
            {{ isEditing ? '保存' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {ref, reactive, onMounted,watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Search} from '@element-plus/icons-vue'
import {
  listAdmins,
  createAdmin,
  updateAdmin,
  deleteAdmin,
  resetAdminPassword
} from '@/api/apiList/admin'
const form = reactive({
  adId: null,
  adAccount: '',
  adPassword: '',
  adName: '',
  phone: '',
  role: ''
})
// 管理员列表 & 分页
const admins = ref([])
const filters = reactive({ name: '', role: '' })
const adminPagination = reactive({ current: 1, size: 10, total: 0 })
async function fetchAdmins() {
  try {
    const data = await listAdmins(filters.name, adminPagination.current, adminPagination.size, filters.role)
    admins.value = data.records
    adminPagination.total = data.total
  } catch {
    ElMessage.error('获取管理员列表失败')
  }
}
const rules = {
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  adAccount: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  adName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '手机号格式不正确',
      trigger: 'blur'
    }
  ]
}

async function confirmResetPassword(id) {
  try {
    const admin = admins.value.find(a => a.adId === id)
    if (!admin) {
      return ElMessage.error('未找到该用户')
    }

    const message =
        admin.role === '管理员'
            ? '确认将密码重置为与账号一致？'
            : '确认要将该用户密码重置为其手机号后6位？'

    const successMessage =
        admin.role === '管理员'
            ? '已成功重置密码为账号'
            : '已成功重置密码（手机号后6位）'

    await ElMessageBox.confirm(message, '重置密码', { type: 'warning' })

    await resetAdminPassword(id)
    ElMessage.success(successMessage)
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('重置密码失败：' + (err.message || '请稍后重试'))
    }
  }
}

function handleAdminPageChange(p) {
  adminPagination.current = p;
  fetchAdmins()
}

function handleAdminSizeChange(s) {
  adminPagination.size = s;
  adminPagination.current = 1;
  fetchAdmins()
}

// 创建/编辑管理员
const showEditDialog = ref(false)
const isEditing = ref(false)

// 当角色切换为"健康管家"时，自动设置账号为手机号
watch(() => form.role, newRole => {
  if (newRole === '健康管家' && form.phone) {
    form.adAccount = form.phone
  }
})

// 当电话改变且当前角色是健康管家，同步账号
watch(() => form.phone, newPhone => {
  if (form.role === '健康管家') {
    form.adAccount = newPhone
  }
})


// 打开对话框时，根据编辑/新建初始化 form
function openCreateDialog() {
  isEditing.value = false
  resetForm()
  showEditDialog.value = true
}
function toEdit(id) {
  const admin = admins.value.find(a => a.adId === id)
  if (!admin) {
    return ElMessage.error('未找到该管理员')
  }
  isEditing.value = true
  Object.assign(form, {
    adId:      admin.adId,
    role:      admin.role,
    adName:    admin.adName,
    adAccount: admin.adAccount,
    phone:     admin.phone
  })
  showEditDialog.value = true
}

// 重置表单
function resetForm() {
  Object.assign(form, {
    adId: null,
    role: '',
    adName: '',
    adAccount: '',
    phone: ''
  })
}

// 提交
async function submitForm() {
  try {
    // 验证所有必填项
    if (!form.role || !form.adAccount || !form.adName || !form.phone) {
      return ElMessage.error('请填写所有必填项')
    }
    let generatedPassword = ''
    if (form.role === '管理员') {
      generatedPassword = form.adAccount
    } else if (form.role === '健康管家') {
      generatedPassword = form.phone.slice(-6)
    }
    const payload = {
      adId: form.adId,
      role: form.role,
      adName: form.adName,
      adAccount: form.adAccount,
      adPassword: generatedPassword,
      phone: form.phone
    }

    if (isEditing.value) {
      await updateAdmin(payload)
      ElMessage.success('更新成功')
    } else {
      await createAdmin(payload)
      ElMessage.success('创建成功')
    }
    showEditDialog.value = false
    fetchAdmins()
  } catch {
    ElMessage.error((isEditing.value ? '更新' : '创建') + '失败')
  }
}

function syncPasswordFromPhone() {
  if (!isEditing.value && form.phone?.length >= 6) {
    form.adPassword = form.phone.slice(-6)
  }
}

async function onDelete(id) {
  try {
    await ElMessageBox.confirm('确认删除？', '提示', {type: 'warning'})
    await deleteAdmin(id)
    ElMessage.success('删除成功')
    fetchAdmins()
  } catch {
  }
}



onMounted(fetchAdmins)
</script>

<style scoped>
/* 工具栏整体样式 */
.toolbar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
  background-color: #f9f9f9;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.04);
}

/* 表格统一边距 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

/* 空状态提示 */
.empty {
  text-align: center;
  margin-top: 40px;
  color: #999;
  font-size: 14px;
}

/* 分页居中 */
.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

/* 弹窗样式增强 */
.admin-dialog .el-dialog__body {
  padding: 28px 40px;
  background-color: #fbfbfb;
}
.dialog-footer {
  text-align: right;
  padding: 12px 40px 24px;
}
.dialog-footer .el-button {
  min-width: 100px;
  border-radius: 20px;
  margin-left: 10px;
}
.admin-form {
  max-width: 420px;
  margin: 0 auto;
}

/* 输入框/选择框样式优化 */
.el-input, .el-select {
  border-radius: 6px;
}

/* 按钮统一圆角 */
.el-button {
  border-radius: 6px;
}

/* 重置按钮绿色样式 */
.el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

</style>
